import { SettingDrawer, PageLoading, Settings as LayoutSettings } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { history, Link, getDvaApp, Dispatch } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import $utils from '@/utils/utils';
import defaultSettings from '../config/defaultSettings';
import { getRegionData } from '@/services/user';
import CommonModule from '@/models/common';
import { ConfigProvider } from 'antd';

import locale from 'antd/es/locale/zh_CN';

const loginPath = ['/user/login', '/user/login/', '/user/pwd'];

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  checkUserInfo?: () => Promise<API.CurrentUser | undefined>;
  setRegionList?: (user: API.CurrentUser) => Promise<void>;
}> {
  const checkUserInfo = () => {
    try {
      const userInfo = $utils.getStorage('user_info');

      $utils.setStorage('user_info', userInfo, 2 * 3600 * 1000);
      return userInfo;
    } catch (error) {
      history.push(loginPath[0]);
    }
    return undefined;
  };
  // 获取地址编码列表
  const setRegionList = async (user: API.CurrentUser) => {
    await getRegionData(user);
  };
  // 如果是登录页面，不执行
  if (!loginPath.includes(history.location.pathname)) {
    const currentUser = checkUserInfo();
    return {
      checkUserInfo,
      currentUser,
      settings: defaultSettings,
    };
  }
  return {
    setRegionList,
    checkUserInfo,
    settings: defaultSettings,
  };
}

function handleMenuItem(dispatch: Dispatch, menuItem: any) {
  const { name, path } = menuItem;
  const currentUrl = window.location.pathname,
    tabList = CommonModule.state.tabList;
  const currentTab = tabList?.length > 0 && tabList.find((item) => item.path === currentUrl),
    toTab = tabList?.length > 0 && tabList.find((item) => item.name === name);
  if (currentTab && ['create', 'update'].includes(currentTab.state?.status)) {
    Modal.confirm({
      title: '警告！',
      icon: <ExclamationCircleOutlined />,
      content: '您可能有修改尚未保存，确定要跳转新页面吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // 设置当前tab对象
        $utils.setNewTab(dispatch, toTab || { name, path, isTopMenu: true });
        $utils.addTab(dispatch, toTab || { name, path, isTopMenu: true });
      },
    });
  } else {
    // 设置当前tab对象
    $utils.setNewTab(dispatch, toTab || { name, path, isTopMenu: true });
    $utils.addTab(dispatch, toTab || { name, path, isTopMenu: true });
  }
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  // 解决无法调用dispatch
  const dispatch = getDvaApp()._store.dispatch;
  return {
    logo: false,
    rightContentRender: (rightProps) => <RightContent {...rightProps} />,
    disableContentMargin: false,
    footerRender: () => <Footer />,
    breadcrumbRender: false,
    menuItemRender: (menuItemProps, defaultDom) => {
      if (menuItemProps.isUrl || !menuItemProps.path || location.pathname === menuItemProps.path) {
        return defaultDom;
      }
      return (
        <div
          onClick={() => {
            handleMenuItem(dispatch, menuItemProps);
          }}
        >
          {defaultDom}
        </div>
      );
    },
    onPageChange: () => {
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && !loginPath.includes(history.location.pathname)) {
        history.push(loginPath[0]);
      }
    },
    pageTitleRender: false,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <ConfigProvider locale={locale}>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            <SettingDrawer
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings: any) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </ConfigProvider>
      );
    },
    ...initialState?.settings,
  };
};
